import { PayloadAction, createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import { Category } from "../../types/category";
import { getCategories, getCategoryById } from "./categoriesAPI";
import { RootState } from "../../app/store";

export interface CategoriesState {
    data: ReadonlyArray<Category>;
    loading: boolean;
    loaded: boolean;
    error: Error | string | null;
    status: "idle" | "loading" | "failed";
}

const initialState: CategoriesState = {
    data: [],
    loading: false,
    loaded: false,
    error: null,
    status: "idle"
}

export const fetchCategories = createAsyncThunk(
    'chat/fetchCategories',
    async () => {
        const response = await getCategories();

        return response;
});

export const fetchCateryById  =  createAsyncThunk(
    'chat/fetchCateryById',
    async (key: string)  =>  {
        const response  = await getCategoryById(key);

        return response;
    }
);

const categoriesSlice = createSlice({
    name: 'categories',
    initialState,
    reducers: {
        startLoading(state) {
            state.loading = true;
        },
        categoriesLoaded(state, action: PayloadAction<Category[]>) {
            state.data = action.payload;
            state.loading = false;
            state.loaded = true;
            state.error = null;
            state.status = "idle";
        },
        categoriesError(state, action: PayloadAction<string>) {
            state.loading = false;
            state.loaded = false;
            state.error = action.payload;
        }
    },
    extraReducers: (builder) => {
        builder
            .addCase(fetchCategories.pending, (state) => {
                state.status = "loading";
            })
            .addCase(fetchCategories.fulfilled, (state, action) => {
                state.status = "idle";
                state.data = action.payload;
            })
            .addCase(fetchCategories.rejected, (state) => {
                state.status = "failed";
            })
            .addCase(fetchCateryById.pending, (state) => {
                state.status = "loading";
            })
            .addCase(fetchCateryById.fulfilled, (state, action) => {
                state.status = "idle";
                console.log(action, 'in slice')
            })
            .addCase(fetchCateryById.rejected, (state) => {
                state.status = "failed";
            });
    }
})

export const { startLoading, categoriesLoaded, categoriesError } = categoriesSlice.actions;

export const selectCategories = (state: RootState) => state.categories.data;
export const selectCategoryById = (state: RootState, key: string) => state.categories.data.find(category => category.key === key);
export const selectLoading = (state: RootState) => state.categories.loading;

export default categoriesSlice.reducer;
